š Data Structures & Java Collections Framework
Linear structures (Arrays, LinkedList, Stack, Queue) store data sequentially. Non-linear structures (Trees, Graphs) store data hierarchically. Java provides built-in collections in the java.util package.
1. What type of data structure stores elements sequentially one after another in memory?
Explanation: Linear structures like Arrays, LinkedLists, Stacks, and Queues arrange elements sequentially.
2. Which of the following is an example of a non-linear data structure?
Explanation: Binary Trees and Graphs organize data hierarchically and multi-directionally, making them non-linear.
3. Which Java package contains the Java Collections Framework classes like ArrayList and HashMap?
Explanation: The Java Collections Framework lives in java.util.
4. What is the fundamental difference between standard Java arrays and ArrayList?
Explanation: Standard arrays cannot change length after creation, whereas ArrayList resizes automatically.
Answer: In linear data structures (Array, LinkedList, Stack, Queue), elements are arranged sequentially and traversed one by one. In non-linear data structures (Tree, Graph), elements are arranged hierarchically or interconnected across multiple levels.
Answer: JCF is a standardized architecture in java.util consisting of core interfaces (Collection, List, Set, Queue, Map), implementations (ArrayList, LinkedList, HashSet, HashMap), and utility algorithms (Collections.sort()).
Answer: Static data structures have a fixed size allocated at compile time (like standard Java arrays). Dynamic data structures can grow and shrink in memory during runtime (like ArrayList and LinkedList).
Answer: Time complexity (number of operations relative to input size) and Space complexity (auxiliary memory consumed relative to input size).
š Asymptotic Notations & Big-O
O(1) is constant time. O(log N) is logarithmic time (divide and conquer). O(N) is linear time. O(N²) is quadratic time (nested loops). Faster algorithms use lower time complexities.
š 7. Circular Linked List (CLL) ā Node Linking & Traversal
In a Circular Linked List, the tail node's next reference loops back to head instead of terminating at null.
head āāāŗ [ 10 | ⢠] āāāŗ [ 20 | ⢠] āāāŗ [ 30 | ⢠] āāā
ā² ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
1. What is the time complexity of looking up an array element by its index (e.g. arr[i])?
Explanation: Array index lookup is O(1) because memory address is calculated instantly from base address.
2. What time complexity does a single loop traversing through N elements have?
Explanation: Visiting N elements once runs in O(N) linear time.
3. Which Big-O notation represents the fastest running time among the options?
Explanation: O(1) constant time performs a fixed number of operations regardless of input size.
4. What is the time complexity of two nested loops of size N each?
Explanation: Nested loops running N iterations each yield O(N * N) = O(N²).
Answer: Big-O notation describes the worst-case asymptotic upper bound of time or memory growth as input size N grows, allowing algorithmic comparisons independent of specific hardware.
Answer: From fastest to slowest: O(1) < O(log N) < O(N) < O(N²).
Answer: Space complexity is total memory required by the algorithm (including inputs). Auxiliary space is the extra or temporary working memory used beyond the input size.
Answer: Two nested loops iterating N times each result in N * N = O(N²) quadratic time complexity.
ArrayList like an expandable rubber band folder: when it fills up with papers, it automatically buys a 50% larger folder in the background and moves everything over!
š Array Reversal & ArrayList Operations
Reversing an array can be done in-place using two pointers. ArrayList provides methods like .add(), .remove(), .get(), and .size().
š 7. Circular Linked List (CLL) ā Node Linking & Traversal
In a Circular Linked List, the tail node's next reference loops back to head instead of terminating at null.
head āāāŗ [ 10 | ⢠] āāāŗ [ 20 | ⢠] āāāŗ [ 30 | ⢠] āāā
ā² ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
1. What is the time complexity of inserting an element at index 0 of an ArrayList?
Explanation: Inserting at index 0 requires shifting all N elements one position to the right: O(N).
2. What is the amortized time complexity of adding an element to the end of an ArrayList?
Explanation: Appending at the end takes O(1) amortized constant time.
3. What technique reverses an array in-place without using extra memory?
Explanation: Two pointers at left and right swap values moving inward in O(N) time and O(1) space.
4. What does the Kadane algorithm find in an array?
Explanation: Kadane algorithm finds the contiguous subarray with the largest sum in O(N) time.
Answer: When full, ArrayList creates a new larger internal array (typically 1.5 times the old capacity), copies all elements over using System.arraycopy(), and discards the old array.
Answer: Adding at the end is amortized O(1). Inserting at index 0 is O(N) because all existing elements must shift one position right.
Answer: Use two pointers: initialize left at 0 and right at length-1. Swap elements at left and right, then increment left and decrement right until they meet.
Answer: Kadane algorithm finds the maximum subarray sum in an array in O(N) linear time and O(1) space.
StringBuilder like an erasable whiteboard where you can quickly scribble and modify sentences without buying a new whiteboard each time!
š Checking Palindromes with StringBuilder
A palindrome reads the same forwards and backwards (e.g. "radar"). StringBuilder provides a built-in .reverse() method.
š 7. Circular Linked List (CLL) ā Node Linking & Traversal
In a Circular Linked List, the tail node's next reference loops back to head instead of terminating at null.
head āāāŗ [ 10 | ⢠] āāāŗ [ 20 | ⢠] āāāŗ [ 30 | ⢠] āāā
ā² ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
1. What is a palindrome string?
Explanation: Words like "radar" or "level" read identically in reverse.
2. What is the time complexity of repeatedly appending characters in a loop using += on String?
Explanation: Because String is immutable, copying on each iteration leads to O(N²) time.
3. Which class should be used for efficient string modifications in single-threaded algorithms?
Explanation: StringBuilder is mutable and avoids object duplication overhead.
4. How can you test if two words are anagrams in O(N) linear time?
Explanation: An integer frequency array counts occurrences of characters in O(N) time.
Answer: Because String is immutable, each += creates a new String object and copies all characters, leading to O(N²) time. StringBuilder.append() runs in O(1) amortized time, giving O(N) total time.
Answer: Sort both strings and compare if Arrays.equals(s1, s2) in O(N log N), or count character frequencies in an array of size 256 in O(N) linear time.
Answer: A substring is contiguous characters within a string. A subsequence maintains relative character order but elements do not need to be contiguous.
Answer: StringBuilder is non-synchronized and faster (best for single-threaded code). StringBuffer has synchronized methods for thread safety.
next and optionally prev). Unlike static arrays, linked lists allow instantaneous O(1) insertions and deletions at the head without memory shifting. Master complete implementations of First Add, Middle Add, Last Add and First Remove, Middle Remove, Last Remove for both Singly and Doubly Linked Lists in Java.
š 1. Singly Linked List (SLL) ā Architecture & Traversal
In Java, each node is an object containing a data payload and a reference pointing to the next Node. Traversal proceeds sequentially until reaching null.
head āāāŗ [ data: 10 | next: ⢠] āāāŗ [ data: 20 | next: ⢠] āāāŗ [ data: 30 | next: null ]
š 2. SLL Insertions ā First Add, Middle Add & Last Add
Implement all three insertion strategies in Java with proper pointer handling:
- First Add (Prepend to Head):
O(1)time. ConfigurenewNode.next = headand updatehead = newNode. - Middle Add (Insert at 0-based Index):
O(N)time. Traverse toindex - 1, assignnewNode.next = curr.next, and updatecurr.next = newNode. - Last Add (Append to Tail):
O(N)time (orO(1)with tail pointer). Traverse untilcurr.next == null, then attachcurr.next = newNode.
š 3. SLL Deletions ā First Remove, Middle Remove & Last Remove
Observe safe node removals and JVM garbage-collection unreferencing:
- First Remove:
O(1)time. Pointhead = head.next. - Middle Remove:
O(N)time. Advance to predecessor node and bridge around target:curr.next = curr.next.next. - Last Remove:
O(N)time. Stop at second-to-last node wherecurr.next.next == null, then setcurr.next = null.
š 4. Doubly Linked List (DLL) ā Architecture & Bidirectional Traversal
In a Java DLL, each node class holds Node prev and Node next pointers, enabling forward and reverse iteration seamlessly.
null <āā [ prev | data: 10 | next ] āāāāŗ [ prev | data: 20 | next ] āāāāŗ [ prev | data: 30 | next ] āāāŗ null
š 5. DLL Insertions ā First Add, Middle Add & Last Add
Execute two-way pointer updates for all DLL add operations:
- First Add:
O(1)time. ConfigurenewNode.next = head,head.prev = newNode, andhead = newNode. - Middle Add:
O(N)time. Re-route four references:newNode.next = curr.next,newNode.prev = curr,curr.next.prev = newNode, andcurr.next = newNode. - Last Add:
O(N)time (orO(1)with tail). Connecttail.next = newNodeandnewNode.prev = tail.
š 6. DLL Deletions ā First Remove, Middle Remove & Last Remove
Remove nodes from any Doubly Linked List index without leaving dangling references:
- First Remove:
O(1)time. Sethead = head.nextand ifhead != null, assignhead.prev = null. - Middle Remove:
O(N)time. Re-route neighbors:curr.prev.next = curr.nextandcurr.next.prev = curr.prev. - Last Remove:
O(N)time. Traverse to tail node and detach it:curr.prev.next = null.
š 7. Circular Linked List (CLL) ā Node Linking & Traversal
In a Circular Linked List, the tail node's next reference loops back to head instead of terminating at null.
head āāāŗ [ 10 | ⢠] āāāŗ [ 20 | ⢠] āāāŗ [ 30 | ⢠] āāā
ā² ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
š 7. Circular Linked List (CLL) ā Node Linking & Traversal
In a Circular Linked List, the tail node's next reference loops back to head instead of terminating at null.
head āāāŗ [ 10 | ⢠] āāāŗ [ 20 | ⢠] āāāŗ [ 30 | ⢠] āāā
ā² ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
1. What two components make up a standard singly linked list node in Java?
Explanation: A Singly Linked List node contains data and an object reference pointing to the next node.
2. What is the time complexity of First Add (inserting at the head) in a linked list?
Explanation: Inserting at the head merely reassigns reference pointers, executing strictly in O(1) time without shifting.
3. What algorithm detects cycles in a linked list using slow and fast pointers?
Explanation: Floyd Tortoise and Hare algorithm detects loops in linked lists in O(N) time and O(1) auxiliary space.
4. What pointer reference does a Doubly Linked List have that a Singly Linked List does not?
Explanation: Doubly Linked List nodes maintain both prev and next pointers, facilitating bidirectional traversal.
Answer: Dynamic sizing (no fixed capacity limits or expensive resizing reallocations) and O(1) constant time insertions and deletions at known pointer locations without shifting elements.
Answer: Using Floyd Cycle Detection Algorithm (Slow and Fast Pointers): move slow pointer by 1 step and fast pointer by 2 steps. If they meet (slow == fast), a cycle exists.
Answer: O(N) time using two pointers: slow moves 1 step while fast moves 2 steps. When fast reaches the end (fast == null || fast.next == null), slow points to the exact middle node.
Answer: A Singly Linked List has only a next pointer (forward only, lower memory). A Doubly Linked List has both next and prev pointers (bidirectional, allows O(1) deletions given node pointer, slightly higher memory per node).
š Valid Parentheses Problem (Stack Application)
Solve the classic bracket-matching problem using java.util.Stack in $O(N)$ time.
š Stack Operations (push, pop, peek)
push() adds an element to the top. pop() removes and returns the top element. peek() inspects the top element without removing it. All operations take O(1) time.
š 7. Circular Linked List (CLL) ā Node Linking & Traversal
In a Circular Linked List, the tail node's next reference loops back to head instead of terminating at null.
head āāāŗ [ 10 | ⢠] āāāŗ [ 20 | ⢠] āāāŗ [ 30 | ⢠] āāā
ā² ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
1. What principle does a Stack data structure follow?
Explanation: Stacks strictly operate under the LIFO principle.
2. Which method inspects the top element of a Stack without removing it?
Explanation: peek() returns the top element without removing it from the stack.
3. What is the time complexity of push and pop operations on a Stack?
Explanation: Top operations on a stack execute in O(1) constant time.
4. Which problem is classically solved using a Stack?
Explanation: Matching opening and closing brackets is solved in O(N) time with a stack.
Answer: LIFO stands for Last-In, First-Out. The most recently added element is always the first one to be removed.
Answer: Iterate through characters: push opening brackets onto the stack. For closing brackets, pop the top and check if they match. If stack is empty at the end, it is balanced.
Answer: Java throws an EmptyStackException.
Answer: Browser Back/Forward navigation, Undo/Redo mechanisms in text editors, and JVM method call frames (Call Stack).
š Queue Operations (add, poll, peek)
In a Queue, elements are added at the rear (enqueue/add) and removed from the front (dequeue/poll). In Java, LinkedList or ArrayDeque implements Queue.
š 7. Circular Linked List (CLL) ā Node Linking & Traversal
In a Circular Linked List, the tail node's next reference loops back to head instead of terminating at null.
head āāāŗ [ 10 | ⢠] āāāŗ [ 20 | ⢠] āāāŗ [ 30 | ⢠] āāā
ā² ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
1. What principle does a Queue data structure follow?
Explanation: Queues process items in First-In, First-Out order.
2. Which method retrieves and removes the front element of a Queue in Java?
Explanation: poll() removes and returns the head of the queue.
3. What does Deque stand for?
Explanation: Deque stands for Double-Ended Queue.
4. Which graph traversal algorithm uses a Queue to visit nodes level-by-level?
Explanation: BFS uses a Queue to visit all adjacent neighbors at the current depth level first.
Answer: FIFO stands for First-In, First-Out. The element added first is the first one to be processed and removed.
Answer: Queue allows insertion at the back and deletion from the front. Deque (Double-Ended Queue) supports insertions and deletions at both ends (front and rear).
Answer: ArrayDeque has better cache locality, requires less memory (no node objects with pointer overhead), and offers faster operations.
Answer: Breadth-First Search (BFS) uses a Queue to explore neighbor nodes level by level.
HashMap like a massive post office wall of numbered mailboxes: hashing turns a resident's name into a direct mailbox slot in O(1) instantaneous time!
š Key-Value Storage with HashMap
HashMap stores key-value pairs. Use .put(k, v) to insert, .get(k) to retrieve, and .containsKey(k) to check existence in O(1) average time.
š 7. Circular Linked List (CLL) ā Node Linking & Traversal
In a Circular Linked List, the tail node's next reference loops back to head instead of terminating at null.
head āāāŗ [ 10 | ⢠] āāāŗ [ 20 | ⢠] āāāŗ [ 30 | ⢠] āāā
ā² ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
1. What is the average time complexity of get() and put() in a HashMap?
Explanation: HashMap achieves O(1) average time complexity through hash indexing.
2. What happens in a HashSet if you add an element that already exists in the set?
Explanation: HashSet automatically ignores duplicates and stores only unique elements.
3. In Java 8+, what data structure does a HashMap bucket convert to when collision length exceeds 8?
Explanation: Buckets with > 8 entries become balanced Red-Black Trees for O(log N) lookups.
4. What method checks whether a specific key exists in a HashMap?
Explanation: containsKey() returns true if the map contains a mapping for the specified key.
Answer: HashMap uses an array of buckets (Node<K,V>[]). It calculates hash(key) to find the bucket index. If multiple keys hash to the same bucket (collision), they are chained in a LinkedList. Starting in Java 8, if a bucket exceeds 8 nodes, it transforms into a Red-Black Tree for O(log N) lookup.
Answer: If two objects are equal according to equals(), their hashCode() must return the same integer. If two objects have the same hashCode(), they are not necessarily equal (hash collision).
Answer: Average time complexity is O(1) constant time. Worst-case (when all keys collide into one bucket) is O(N) or O(log N) with Red-Black tree bins.
Answer: HashMap stores key-value pairs (implements Map). HashSet stores only unique values without duplicates (internally backed by a HashMap).
š Factorial with Recursion
Every recursive method requires a base case to terminate and prevent infinite call stack execution.
š 7. Circular Linked List (CLL) ā Node Linking & Traversal
In a Circular Linked List, the tail node's next reference loops back to head instead of terminating at null.
head āāāŗ [ 10 | ⢠] āāāŗ [ 20 | ⢠] āāāŗ [ 30 | ⢠] āāā
ā² ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
1. What happens if a recursive function does not define a valid base case?
Explanation: Without a base case, recursive calls exhaust call stack memory: StackOverflowError.
2. What is the value of 5! (factorial of 5)?
Explanation: 5! = 5 * 4 * 3 * 2 * 1 = 120.
3. What classical puzzle is solved using Backtracking?
Explanation: N-Queens and Sudoku are classic backtracking problems.
4. Where does the JVM store active frames for recursive method invocations?
Explanation: Method invocations and their local parameters are pushed onto the Call Stack.
Answer: A base case is the condition where the recursive method stops calling itself. Without a base case, recursion continues indefinitely until a StackOverflowError occurs.
Answer: The Call Stack in JVM memory stores stack frames for each active recursive call.
Answer: Plain recursion breaks a problem down into sub-problems. Backtracking is an algorithmic approach that explores choices recursively and undoes (backtracks) past decisions when a dead end is reached (e.g., N-Queens, Sudoku).
Answer: A recursive function where the recursive call is the very last operation performed before returning, allowing potential compiler optimizations.
š Linear Search & Binary Search
Linear search works on both unsorted and sorted arrays with O(N) time complexity. Binary search requires the array to be sorted beforehand and achieves O(log N) time by eliminating half of the search range at every comparison.
š 7. Circular Linked List (CLL) ā Node Linking & Traversal
In a Circular Linked List, the tail node's next reference loops back to head instead of terminating at null.
head āāāŗ [ 10 | ⢠] āāāŗ [ 20 | ⢠] āāāŗ [ 30 | ⢠] āāā
ā² ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
1. What condition is strictly required before running Binary Search on an array?
Explanation: Binary Search requires sorted elements to decide whether to search left or right.
2. What is the worst-case time complexity of Binary Search on an array of size N?
Explanation: Binary Search halves the search space at each iteration, giving O(log N).
3. What is the time complexity of Linear Search in the worst case?
Explanation: Linear Search may have to inspect all N elements when target is at the end or not present.
4. Why is `mid = low + (high - low) / 2` written instead of `(low + high) / 2`?
Explanation: Adding low and high directly can exceed Integer.MAX_VALUE and cause overflow.
Answer: The elements in the array must already be sorted in ascending or descending order. Without sorting, binary halving cannot guarantee eliminating the correct half.
Answer: When low and high are very large integers near Integer.MAX_VALUE, `low + high` causes integer arithmetic overflow into negative numbers. Using `low + (high - low) / 2` completely avoids this overflow.
Answer: Best case is O(1) when the target is at the exact middle index. Average and worst-case complexities are both O(log N).
Answer: Linear search is preferred when the dataset is unsorted and will only be searched once (since sorting first would take O(N log N)), or when data size N is extremely small.
š Comparison Sorts & Merge Sort
Bubble Sort repeatedly swaps adjacent out-of-order elements with O(N²) time. Merge Sort uses Divide and Conquer: it splits the array into two halves, recursively sorts them, and merges them back in O(N log N) time.
š 7. Circular Linked List (CLL) ā Node Linking & Traversal
In a Circular Linked List, the tail node's next reference loops back to head instead of terminating at null.
head āāāŗ [ 10 | ⢠] āāāŗ [ 20 | ⢠] āāāŗ [ 30 | ⢠] āāā
ā² ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
1. What is the worst-case time complexity of Bubble Sort?
Explanation: Bubble Sort uses nested loops to compare adjacent items, requiring O(N²) worst-case comparisons.
2. What is the guaranteed worst-case time complexity of Merge Sort?
Explanation: Merge Sort always splits in half and merges in linear time, guaranteeing O(N log N).
3. What is the auxiliary space complexity of Merge Sort?
Explanation: Merge Sort allocates temporary arrays proportional to N to merge sub-arrays.
4. What is a stable sort in Java?
Explanation: Stable sorts preserve the original order of duplicate keys.
Answer: A stable sorting algorithm preserves the original relative order of elements that have equal keys or values (e.g., Merge Sort, Insertion Sort). Unstable sorts may reorder them (e.g., QuickSort, HeapSort).
Answer: Merge sort has guaranteed O(N log N) time complexity in best, average, and worst cases. Its space complexity is O(N) because of auxiliary arrays used during merging.
Answer: For primitives (int, double, etc.), Java uses Dual-Pivot Quicksort (O(N log N) average, in-place). For objects (String, custom classes), Java uses TimSort (an adaptive stable merge sort variant).
Answer: QuickSort sorts in-place without allocating O(N) extra memory arrays, and exhibits superior CPU cache locality.
š Opposite Direction & Fast/Slow Pointers
Opposite-end pointers solve Two Sum on sorted arrays, array reversal, and palindrome checks in O(N) time with O(1) space. Fast and slow pointers (Floyd cycle detection) detect loops in linked lists.
š 7. Circular Linked List (CLL) ā Node Linking & Traversal
In a Circular Linked List, the tail node's next reference loops back to head instead of terminating at null.
head āāāŗ [ 10 | ⢠] āāāŗ [ 20 | ⢠] āāāŗ [ 30 | ⢠] āāā
ā² ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
1. What is the time complexity of reversing an array using two pointers moving towards each other?
Explanation: Left and right pointers meet at the center, traversing N/2 elements which is O(N) time.
2. In a sorted array, if arr[left] + arr[right] is greater than target, which pointer should move?
Explanation: Decreasing right moves to a smaller element, reducing the total sum.
3. What technique detects cycles in a linked list using slow and fast pointers?
Explanation: Floyd Tortoise and Hare algorithm detects linked list loops in O(N) time and O(1) space.
4. What is the auxiliary space complexity of two pointers on an array?
Explanation: Two pointers only use two integer variables (left, right), requiring O(1) auxiliary space.
Answer: Place left pointer at 0 and right at n-1. Calculate current sum = arr[left] + arr[right]. If current sum == target, return indices. If sum < target, left++ to increase sum. If sum > target, right-- to decrease sum.
Answer: A two pointer technique where a slow pointer advances 1 step and a fast pointer advances 2 steps. If a cycle exists in the linked list, the fast pointer will eventually overlap with the slow pointer.
Answer: Nested loops take O(N²) time. By sorting and applying two pointers, time complexity drops to O(N log N) sorting + O(N) traversal = O(N log N), or O(N) if already sorted.
Answer: Yes, strings can be checked for palindromes or vowels reversed by either converting to a char array (`s.toCharArray()`) or using two index variables with `charAt()`.
š Fixed & Dynamic Sliding Window
In a fixed window of size K, we subtract the element leaving the window and add the new incoming element in O(1) per step. In a dynamic window, the right pointer expands the window and the left pointer shrinks it when constraints are violated.
š 7. Circular Linked List (CLL) ā Node Linking & Traversal
In a Circular Linked List, the tail node's next reference loops back to head instead of terminating at null.
head āāāŗ [ 10 | ⢠] āāāŗ [ 20 | ⢠] āāāŗ [ 30 | ⢠] āāā
ā² ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
1. What is the time complexity of finding the maximum sum of all subarrays of size K using sliding window?
Explanation: Sliding window updates window sum in O(1) per step, traversing the array in O(N) total time.
2. When sliding a fixed window of size K from index i to i+1, how is the sum updated?
Explanation: Sliding window updates sum in O(1) by adding incoming item and subtracting outgoing item.
3. What happens to the left pointer in a variable-size sliding window when the constraint is violated?
Explanation: Advancing the left pointer contracts the window until the constraint is restored.
4. Which problem is NOT ideal for variable-size sliding window without prefix sums?
Explanation: Negative numbers break the monotonic expansion/contraction property of sliding windows.
Answer: Brute force recalculates subarray sums or properties in O(N * K) time. Sliding window reuses results from the previous window by subtracting outgoing and adding incoming elements in O(1), achieving O(N) overall time.
Answer: Fixed-size maintains a constant window width K (e.g., maximum sum subarray of size K). Variable-size expands right to satisfy a condition and contracts left to find the minimum/maximum valid length (e.g., smallest subarray with sum >= S).
Answer: A HashMap or integer frequency array `int[128]` / `int[256]` to count character frequencies within the current active window.
Answer: For variable-size windows searching for a target sum, negative numbers invalidate window shrinking monotonicity (shrinking may increase or decrease sum). In such cases, Prefix Sum + HashMap is required.
š BST Structure & In-Order Traversal
In a BST, lookup, insertion, and deletion take O(log N) time on average. In-order traversal (Left, Root, Right) of a Binary Search Tree always outputs all element values in strictly sorted ascending order.
š 7. Circular Linked List (CLL) ā Node Linking & Traversal
In a Circular Linked List, the tail node's next reference loops back to head instead of terminating at null.
head āāāŗ [ 10 | ⢠] āāāŗ [ 20 | ⢠] āāāŗ [ 30 | ⢠] āāā
ā² ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
1. What order of elements is printed by an In-order traversal of a valid Binary Search Tree?
Explanation: In-order traversal (Left, Root, Right) always outputs BST values in ascending sorted order.
2. In a valid BST, where is an element smaller than the root node stored?
Explanation: By BST definition, every node in the left subtree has a value less than the root node.
3. What is the average time complexity of searching a node in a balanced BST of N nodes?
Explanation: Each comparison eliminates half of the remaining tree, giving O(log N) average time.
4. What is the sequence of steps in Post-order tree traversal?
Explanation: Post-order traversal visits left subtree, right subtree, and finally the current root node.
Answer: For every node: all values in its left subtree must be strictly less than node.val, and all values in its right subtree must be strictly greater than node.val.
Answer: In-order traversal (Left subtree -> Current Node -> Right subtree) always visits nodes in ascending sorted order.
Answer: In a skewed or degenerate BST (like a linked list), search is O(N). In a self-balancing BST (like AVL or Red-Black Tree), search is guaranteed O(log N).
Answer: Pre-order (Root, Left, Right), In-order (Left, Root, Right), and Post-order (Left, Right, Root).
PriorityQueue like a VIP emergency lane on an ambulance highway: life-saving emergency vehicles bypass all ordinary traffic!
š Min-Heap & Max-Heap in Java
`PriorityQueue<Integer>` forms a Min-Heap (smallest retrieved first). Supplying `Collections.reverseOrder()` creates a Max-Heap (largest retrieved first). Insertion (`add()`) and removal (`poll()`) run in O(log N) time, while inspecting the top (`peek()`) runs in O(1) time.
š 7. Circular Linked List (CLL) ā Node Linking & Traversal
In a Circular Linked List, the tail node's next reference loops back to head instead of terminating at null.
head āāāŗ [ 10 | ⢠] āāāŗ [ 20 | ⢠] āāāŗ [ 30 | ⢠] āāā
ā² ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
1. What is the default heap ordering of Javaās `java.util.PriorityQueue`?
Explanation: In Java, PriorityQueue is a Min-Heap by default, placing the smallest item at the head.
2. What is the time complexity of the `peek()` operation in Java PriorityQueue?
Explanation: peek() inspects the root element at index 0 of the internal heap array in O(1) constant time.
3. What is the time complexity of inserting an element into a PriorityQueue with `add()`?
Explanation: Adding requires sifting up along tree height, which is O(log N).
4. How do you construct a Max-Heap using Java PriorityQueue?
Explanation: Passing Collections.reverseOrder() reverses the natural comparator, turning it into a Max-Heap.
Answer: In a Min-Heap, the root node holds the minimum element and parent <= children. In a Max-Heap, the root holds the maximum element and parent >= children.
Answer: Javaās `PriorityQueue` implements a Min-Heap by default according to natural ordering. To create a Max-Heap, pass `Collections.reverseOrder()` to its constructor.
Answer: `peek()` is O(1) constant time because the minimum element is at the root. `add()` and `poll()` both take O(log N) time due to heapify (sift-up and sift-down).
Answer: Maintain a Min-Heap of size K. Iterate through the array: add each element to the heap, and if heap size exceeds K, call `poll()`. After inspecting all elements, the heap head is the K-th largest element.
š Breadth-First & Depth-First Search
Breadth-First Search (BFS) traverses level-by-level using a Queue (FIFO) and is optimal for shortest paths in unweighted graphs. Depth-First Search (DFS) explores as deep as possible along each branch using recursion or a Stack (LIFO). A `boolean[] visited` array prevents infinite cycles.
š 7. Circular Linked List (CLL) ā Node Linking & Traversal
In a Circular Linked List, the tail node's next reference loops back to head instead of terminating at null.
head āāāŗ [ 10 | ⢠] āāāŗ [ 20 | ⢠] āāāŗ [ 30 | ⢠] āāā
ā² ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
1. What data structure is used to implement Breadth-First Search (BFS) on a graph?
Explanation: BFS visits nodes level by level in First-In-First-Out order using a Queue.
2. What is the time complexity of BFS and DFS using an Adjacency List?
Explanation: Each vertex and edge is examined once, yielding O(V + E) time complexity.
3. What is the purpose of the `visited` array in graph algorithms?
Explanation: Tracking visited nodes prevents reprocessing nodes in cyclic graphs.
4. Which traversal algorithm finds the shortest path in an unweighted graph?
Explanation: BFS traverses level by level, ensuring the first time a target vertex is reached is via the shortest edge path.
Answer: BFS explores neighbor-by-neighbor in concentric rings using a Queue, making it ideal for shortest path in unweighted graphs. DFS explores deeply down a path before backtracking using recursion or a Stack, making it ideal for cycle detection and topological sorting.
Answer: Using an Adjacency List, both BFS and DFS run in O(V + E) time, where each vertex and edge is processed once.
Answer: Graphs can contain cycles or multiple paths to the same vertex. Without tracking visited vertices, traversal would loop indefinitely in an infinite cycle.
Answer: Adjacency List uses O(V + E) space, making it efficient for sparse graphs (where E << V²). Adjacency Matrix requires O(V²) space regardless of edge count.
š Memoization, Tabulation & Greedy Strategy
DP requires Overlapping Subproblems and Optimal Substructure. Top-Down (Memoization) uses recursion with a cache. Bottom-Up (Tabulation) fills an iterative table. Greedy algorithms pick the best immediate choice without backtracking.
š 7. Circular Linked List (CLL) ā Node Linking & Traversal
In a Circular Linked List, the tail node's next reference loops back to head instead of terminating at null.
head āāāŗ [ 10 | ⢠] āāāŗ [ 20 | ⢠] āāāŗ [ 30 | ⢠] āāā
ā² ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
1. What two properties are required to solve a problem using Dynamic Programming?
Explanation: DP requires overlapping subproblems to cache work and optimal substructure to compose solutions.
2. What is the time complexity of computing Fibonacci numbers using Tabulation DP?
Explanation: Tabulation computes each Fibonacci number once in a single loop from 2 to N, running in O(N) time.
3. What distinguishes Top-Down DP (Memoization) from Bottom-Up DP (Tabulation)?
Explanation: Memoization uses top-down recursion with caching; Tabulation uses bottom-up iteration with a table.
4. How does a Greedy algorithm make decisions?
Explanation: Greedy algorithms choose the locally optimal decision at each step hoping it leads to a global optimum.
Answer: 1) Optimal Substructure (an optimal solution to the problem contains optimal solutions to subproblems), and 2) Overlapping Subproblems (the same subproblems are solved multiple times).
Answer: Top-down is recursive and solves subproblems on-demand while caching them in a table/map. Bottom-up is iterative, solves subproblems from smallest base cases upwards, and avoids recursion stack overhead.
Answer: A greedy algorithm makes the locally optimal choice at each step without ever reconsidering. DP solves all subproblems, remembers their solutions, and guarantees global optimality.
Answer: Naive recursive Fibonacci takes exponential O(2^N) time due to repeating identical branches. DP reduces this to O(N) linear time and O(N) or O(1) space.
š Trie Node Structure & Operations
isEndOfWord indicating if a node marks the termination of a complete dictionary word.
- Insertion: $O(L)$ time complexity. Traverse down character branches; instantiate new nodes whenever a child reference is null.
- Search: $O(L)$ time. Follow child pointers. Returns true only if the path exists AND
isEndOfWord == true. - Prefix Matching (
startsWith): $O(L)$ time. Returns true as long as the entire prefix path exists, regardless of word termination. - Space Complexity: $O(Sigma cdot L cdot N)$ where $Sigma$ is alphabet size (26) and $N$ is total words stored.
š Auto-complete & Bitwise Trie Applications
- Auto-complete: Traverse to the node matching the user's typed prefix, then perform Depth-First Search (DFS) from that node to collect all candidate suffixes.
- Bitwise 0-1 Trie: Stores 32-bit binary representations of integers to solve the Maximum XOR Pair in an Array in $O(N cdot 32)$ instead of $O(N^2)$.
1. What is the time complexity to search a word of length L in a Trie?
Explanation: Searching in a Trie requires traversing at most L edges, independent of the total number of words (N) in the dictionary.
2. How does startsWith(prefix) differ from search(word) in a Trie?
Explanation: A prefix query is satisfied as long as the path exists, even if no complete word ends at that specific node.
3. What is the primary disadvantage of an array-based Trie implementation?
Explanation: Allocating a 26-element array for every node wastes substantial memory when node branching factor is low. Using a
HashMap<Character, TrieNode> mitigates space overhead.
4. Which bitwise problem is optimally solved using a Trie?
Explanation: A binary 0-1 Trie allows greedy choice of opposite bits at each position from MSB to LSB in $O(32)$ time per element.
Answer: While both offer $O(L)$ average lookup, HashSets suffer from hash collisions and cannot perform prefix searches (like auto-complete or startsWith()) efficiently without examining all keys. A Trie naturally organizes shared prefixes and supports sorted lexicographical iteration.
Answer: Using post-order recursion: traverse to the end of the word, set isEndOfWord = false. On the unwind stack, if a node has no other children and is not the end of another word, prune the node (set parent reference to null) to reclaim memory.
Answer: A space-optimized Trie where every non-branching node path is merged with its child into a single edge containing a multi-character string substring (e.g. edge "test" instead of 4 separate single-char nodes 't'-'e'-'s'-'t').
Answer: Instead of searching for each dictionary word independently on a 2D Boggle board, insert all words into a Trie. Then run DFS backtracking across the grid: if the current letter path does not exist in the Trie, prune the entire search branch immediately.
š Path Compression & Union by Rank
- Path Compression: During
find(x), point every visited node directly to the root representative:parent[x] = find(parent[x]). Flattens tree height dramatically. - Union by Rank / Size: Attach the shorter tree beneath the root of the taller tree to prevent depth inflation.
- Amortized Complexity: $O(alpha(N))$ per operation, where $alpha$ is the Inverse Ackermann Function (practically $le 4$ for all conceivable $N le 10^{80}$).
š Cycle Detection & Kruskal's Algorithm
- Sort all edges by weight in non-decreasing order ($O(E log E)$).
- Iterate through edges: if
find(u) != find(v), the edge does not form a cycle. Add it to the MST and merge sets viaunion(u, v). - Repeat until $(V - 1)$ edges are included. Total time: $O(E log E)$.
1. What is the amortized time complexity of DSU with both Path Compression and Union by Rank?
Explanation: Combining path compression and union by rank yields an amortized bound of $O(alpha(N))$, where $alpha$ is the nearly constant Inverse Ackermann function.
2. When does adding an edge (u, v) create a cycle in an undirected graph?
Explanation: If both endpoints $u$ and $v$ already share the same representative root, a path between them already exists; connecting them introduces an alternative path (a cycle).
3. What is the time complexity of Kruskal's algorithm on a graph with V vertices and E edges?
Explanation: The bottleneck is sorting the $E$ edges in non-decreasing order ($O(E log E)$). The subsequent $E$ union-find operations take near-linear $O(E cdot alpha(V))$ time.
4. Can DSU easily support removing an edge from a graph (dynamic disconnection)?
Explanation: Standard DSU does not support edge deletion because path compression destroys tree topology. Rollbacks require maintaining an explicit history stack (DSU with rollback) without path compression.
Answer: Kruskal's algorithm ($O(E log E)$) is simpler and performs faster on sparse graphs ($E ll V^2$) because it works directly on an edge list. Prim's algorithm ($O((V + E) log V)$ with a binary heap or $O(V^2)$ with an adjacency matrix) is better suited for dense graphs ($E approx V^2$).
Answer: Initialize count = N. For each edge (i, j) where isConnected[i][j] == 1, call union(i, j). If union successfully connects two previously disjoint sets, decrement count--. The final value of count is the total number of connected components (provinces).
Answer: No! Standard DSU cannot detect cycles in directed graphs because it only models undirected symmetric equivalence relations. For directed graphs, use DFS with a recursion stack (back-edges) or Kahn's Topological Sort algorithm.
Answer: In Union by Rank, rank approximates the upper bound of tree height, incrementing only when two trees of equal rank are merged. In Union by Size, size[root] tracks the total count of elements in the tree, and the root of the smaller tree is attached to the larger tree.
š Greedy Relaxation with Java PriorityQueue
dist[] initialized to $infty$, setting dist[src] = 0.
- Min-Heap PriorityQueue: Extracts the unsettled vertex with the smallest tentative distance in $O(log V)$.
- Relaxation Condition: For each neighbor $v$ of $u$, if
dist[u] + weight < dist[v], updatedist[v] = dist[u] + weightand push(dist[v], v)into the priority queue. - Time Complexity: $O((V + E) log V)$ using an adjacency list and binary Min-Heap.
- Negative Weights: Dijkstra fails on graphs with negative edge weights or negative cycles! For graphs with negative weights, use the Bellman-Ford algorithm ($O(V cdot E)$).
š Java Implementation Details
Node class implementing Comparable<Node> or provide a custom comparator: PriorityQueue<Node> pq = new PriorityQueue<>(Comparator.comparingInt(n -> n.weight));.
1. Why does Dijkstra's algorithm fail on graphs with negative edge weights?
Explanation: Dijkstra's greedy invariant assumes that expanding paths can only add non-negative cost. A subsequent negative edge can violate an already finalized shortest path.
2. What is the time complexity of Dijkstra using a Min-Heap PriorityQueue?
Explanation: Each vertex is extracted from the heap ($V log V$), and each edge relaxation pushes a new entry into the heap ($E log V$), yielding $O((V + E) log V)$.
3. What does the relaxation step dist[u] + weight < dist[v] accomplish?
Explanation: Edge relaxation checks if reaching $v$ via $u$ is strictly cheaper than the best distance currently known for $v$.
4. Which algorithm should be used instead of Dijkstra when edges have negative weights?
Explanation: Bellman-Ford relaxes all $E$ edges $V - 1$ times, handling negative weights and detecting negative weight cycles in $O(V cdot E)$ time.
if (d > dist[u]) continue; vital in Java Dijkstra?
ā¼
Answer: Java's PriorityQueue does not support efficient $O(log N)$ decreaseKey(). When a shorter path is found, a duplicate PathNode is inserted into the PQ. When the older, stale node with a higher distance is eventually polled, skipping it avoids redundant exploration of all outgoing edges.
Answer: When weights are only 0 or 1, use a double-ended queue (Deque) instead of a PriorityQueue: push 0-weight relaxations to the front (addFirst) and 1-weight relaxations to the back (addLast). This reduces runtime from $O(E log V)$ to optimal linear $O(V + E)$ time.
Answer: Maintain a parent[] array. Whenever relaxation occurs (dist[u] + w < dist[v]), set parent[v] = u. To print the path from source to target, backtrack from target to source using parent pointers and reverse the resulting list.
Answer: Run Dijkstra from the starting signal node $K$. The time for all nodes to receive the signal is $max(dist[1 dots N])$. If any node remains unreachable ($dist[i] == infty$), return -1.
š Kahn's BFS Algorithm (In-Degree Array)
- Compute the in-degree (number of incoming edges) for every vertex in the graph.
- Add all vertices with
inDegree == 0into aQueue(these tasks have zero unresolved prerequisites). - While the queue is not empty, poll vertex $u$, append it to the topological order, and decrement the in-degree of all its neighbors. If a neighbor's in-degree drops to 0, push it into the queue.
- Cycle Detection: If the total number of vertices in the topological order is less than $V$, the graph contains a directed cycle (deadlock / circular dependency)!
š DFS Topological Sort vs Kahn's Algorithm
Stack upon finishing recursion for all descendants. Both algorithms operate in $O(V + E)$ linear time and space.
1. On what kind of graph is Topological Sort strictly defined?
Explanation: A graph with cycles cannot have a topological sort because circular dependencies make linear sequencing mathematically impossible.
2. How does Kahn's algorithm detect a cycle in a directed graph?
Explanation: Vertices trapped in a cycle maintain an in-degree $ge 1$ and can never enter the queue, causing the algorithm to terminate early with fewer than $V$ elements.
3. What does an in-degree of 0 mean for a vertex in Kahn's algorithm?
Explanation: In-degree represents unresolved dependency count. An in-degree of 0 indicates all prerequisites have been satisfied.
4. What is the time complexity of Topological Sort using Kahn's algorithm?
Explanation: Every vertex is pushed into and popped from the queue once ($V$), and each directed edge is inspected once ($E$), yielding linear $O(V + E)$ performance.
Answer: Yes! A DAG can have multiple valid topological sorts whenever multiple vertices have in-degree 0 simultaneously. A topological sort is unique if and only if there is a directed Hamiltonian path through the graph.
Answer: Construct an adjacency list and in-degree array from prerequisite pairs. Run Kahn's BFS. If the total number of dequeued courses equals numCourses, return true (all courses can be finished); otherwise, return false (cycle detected).
Answer: Maintain two boolean tracking arrays: visited[] and inStack[] (recursion stack). When exploring neighbor $v$: if $v$ is already in inStack[], a back-edge exists, confirming a directed cycle. When finishing the DFS call for $u$, pop it by setting inStack[u] = false.
Answer: Compare adjacent words in the sorted dictionary to find the first differing character, creating a directed edge char1 -> char2. Running Kahn's topological sort on this character DAG reconstructs the alphabet order or detects an invalid dictionary.
š Essential Bitwise Operators & Magic Tricks
& (AND), | (OR), ^ (XOR), ~ (Bitwise NOT), << (Left shift), >> (Signed right shift), and >>> (Unsigned right shift).
- Check Odd/Even:
(n & 1) == 0(Even) vs!= 0(Odd). - Clear the lowest set bit:
n & (n - 1)ā Removes the rightmost 1-bit. - Isolate the lowest set bit:
n & (-n)ā Two's complement property. - Check if Power of Two:
n > 0 && (n & (n - 1)) == 0. - Swap without third variable:
a ^= b; b ^= a; a ^= b;. - Count Set Bits (Brian Kernighan's Algorithm): Repeatedly apply
n = n & (n - 1)until $n = 0$; runs in $O( ext{set bits})$.
š Bitmasking & Subset Generation
1. What is the result of expression (n & (n - 1)) on integer n?
Explanation: Subtracting 1 flips all bits after and including the rightmost 1-bit. Performing bitwise AND with original $n$ clears that rightmost 1-bit.
2. What property of XOR allows finding the single unique number in an array where every other element appears twice?
Explanation: Because XOR is commutative and associative, matching pairs cancel out ($a oplus a = 0$), leaving $0 oplus ext{unique} = ext{unique}$.
3. What does the unsigned right shift operator >>> do in Java?
Explanation: Unlike
>> (which sign-extends), >>> performs a logical shift, always filling MSBs with zeros.
4. How do you check if the k-th bit of an integer n is set (1-indexed from right)?
Explanation: Creating a bitmask with
1 << (k - 1) isolates bit $k$. Bitwise AND with $n$ yields non-zero if the bit is 1.
Answer: 1. XOR all numbers to get xorSum = a ^ b.
2. Find the rightmost set bit using diffBit = xorSum & (-xorSum) (at this bit, a and b differ).
3. Partition the array into two buckets based on whether that bit is set, and XOR each bucket independently to isolate a and b in $O(N)$ time and $O(1)$ space.
Answer: $O(1)$ constant time. Java implements a branch-free divide-and-conquer parallel bit-counting algorithm (Hamming weight / popcount), which modern HotSpot compilers map directly to hardware CPU instructions like POPCNT on x86-64.
Answer: Using the classic trick: for (int sub = mask; sub > 0; sub = (sub - 1) & mask) { ... }. This iterates through all submasks in $O(2^k)$ where $k$ is the number of set bits in mask, avoiding $O(2^N)$ iteration.
Answer: If low + high exceeds $2^{31} - 1$, 32-bit signed integer overflow occurs, wrapping to a negative number. Unsigned right shift >>> 1 treats the 32-bit sum as unsigned, yielding the correct positive midpoint even during overflow.
š Why Segment Tree? (Overcoming Brute Force & Prefix Sums)
- Brute Force: Query $O(N)$, Point Update $O(1)$. Total $Q$ queries: $O(Q cdot N)$ (Too slow for $N, Q le 10^5$).
- Prefix Sum Array: Range Sum Query $O(1)$, but Point Update $O(N)$ (fails when updates occur frequently).
- Segment Tree: Tree Construction $O(N)$, Range Query $O(log N)$, Point Update $O(log N)$! Perfect balance for dynamic range workloads.
- Array Representation: A 1D array of size $4N$ is allocated: Root at index 1, left child at $2i$, right child at $2i + 1$.
š Lazy Propagation & Fenwick Tree
1. What is the time complexity to query a range [L, R] in a Segment Tree of size N?
Explanation: At each tree depth level, at most 4 segment nodes are visited, leading to $O(log N)$ total nodes visited.
2. Why is the size of the array representing a Segment Tree commonly sized to 4N?
Explanation: A complete binary tree for $N$ elements requires $2^{lceil log_2 N ceil + 1} - 1$ nodes, which in the worst case (when $N = 2^k + 1$) is bounded strictly below $4N$.
3. What is Lazy Propagation in Segment Trees used for?
Explanation: Without lazy propagation, updating a range $[L, R]$ requires modifying all affected leaf nodes ($O(N log N)$). Lazy propagation caches pending updates in an auxiliary tree array, achieving $O(log N)$.
4. How does a Fenwick Tree (Binary Indexed Tree) compare to a Segment Tree?
Explanation: Fenwick Trees use $O(N)$ space and few lines of bitwise code (
idx += idx & (-idx)), but cannot easily support non-invertible queries like general Range Minimum Query on dynamic updates.
Answer: Prefer a Segment Tree when: 1. The range operation is not easily invertible (e.g., Range Minimum/Maximum Query with arbitrary point/range updates). 2. You need complex Lazy Propagation over custom intervals. 3. You need to store multiple associative attributes (e.g. max prefix sum, max subarray sum).
Answer: Store 4 values in each node: totalSum, prefixSum, suffixSum, and maxSubarraySum. When merging left and right children:
maxSubarraySum = max(left.max, right.max, left.suffixSum + right.prefixSum). All queries run in $O(log N)$.
Answer: When the coordinate range is massive (e.g., $N = 10^9$), allocating a $4N$ array is impossible due to memory limits. A Dynamic (Implicit) Segment Tree instantiates pointer-based nodes only when they are accessed, taking $O(Q log N)$ space for $Q$ queries.
Answer: $O(N)$ linear time. A segment tree has at most $2N - 1$ total nodes. The build function visits each node once and computes the combined value in $O(1)$ time.